package com.zahb.qadx.base;

import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.AnimRes;
import androidx.annotation.LayoutRes;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.StringRes;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;

import com.githang.statusbar.StatusBarCompat;
import com.google.gson.Gson;
import com.orhanobut.logger.AndroidLogAdapter;
import com.orhanobut.logger.Logger;
import com.zahb.qadx.R;
import com.zahb.qadx.buriedpoint.BuriedPoint;
import com.zahb.qadx.util.ActivityManager;
import com.zahb.qadx.util.DisplayUtil;

import butterknife.Unbinder;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;

/**
 * Created on 2018/11/26 17:24.
 *
 * @author zhoudawei
 */
public abstract class BaseActivity extends AppCompatActivity implements View.OnClickListener {

    protected FrameLayout mTopBarContainer;
    protected FrameLayout mTopBarStartContainer;
    protected TextView mTopBarStartText;
    protected FrameLayout mTopBarEndContainer;
    protected TextView mTopBarEndText;
    protected View mTopBarDivider;
    protected FrameLayout mContainer;
    protected LinearLayout mProgressContainer;
    protected ProgressBar mProgressBar;
    protected TextView mProgressText;
    protected TextView mTitle_view;

    protected CompositeDisposable mCompositeDisposable;
    protected Unbinder mUnbinder;

    protected View mToastView;
    protected Toast mToast;
    protected Toast mBindToast;

    protected boolean mAddActivityToCache = true;



    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        Logger.addLogAdapter(new AndroidLogAdapter() {//log日志初始化 与开启关闭
            @Override public boolean isLoggable(int priority, String tag) {
                return false; //开启
            }
        });
        if (mAddActivityToCache)
        ActivityManager.getInstance().addActivity(ActivityManager.KEY_ALL_ACTIVITY, this);
        hideActionBar();
        setContentView(getBaseLayout());
        initBaseViews();
        setContentView();
        setTitleText(getTitleStringRes());
        StatusBarCompat.setStatusBarColor(this, getResources().getColor(R.color.white));

    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mAddActivityToCache)
            ActivityManager.getInstance().removeActivity(ActivityManager.KEY_ALL_ACTIVITY, this);
        clearDisposable();
        if (mUnbinder != null)
            mUnbinder.unbind();
        hideProgressDialog();
        hideBindToast();
    }

    @Override
    public void onClick(View v) {
        // 返回键
        if (v.getId() == R.id.top_bar_start_container) {
            onBackPressed();
        }
    }

    @LayoutRes
    protected int getBaseLayout() {
        return R.layout.activity_base;
    }

    private void initBaseViews() {
        mTopBarContainer = findViewById(R.id.top_bar_container);
        mTopBarStartContainer = findViewById(R.id.top_bar_start_container);
        mTopBarStartContainer.setOnClickListener(this);
        mTopBarStartText = findViewById(R.id.top_bar_start_text);
        mTopBarEndContainer = findViewById(R.id.top_bar_end_container);
        mTopBarEndContainer.setOnClickListener(this);
        mTopBarEndText = findViewById(R.id.top_bar_end_text);
        mTopBarDivider = findViewById(R.id.top_bar_divider);
        mContainer = findViewById(R.id.container);
        mProgressContainer = findViewById(R.id.progress_container);
        mProgressBar = findViewById(R.id.progress_bar);
        mProgressText = findViewById(R.id.progress_text);


    }

    protected void setContentView() {
        if (getLayout() != 0) {
            getLayoutInflater().inflate(getLayout(), mContainer, true);
            initViews();
        }
    }

    @LayoutRes
    abstract protected int getLayout();

    abstract protected void initViews();

    @StringRes
    abstract protected int getTitleStringRes();

    /**
     * 设置标题文本
     */
    protected void setTitleText(@StringRes int stringId) {
        String title="";
        if (stringId != 0){
            setTitleText(getString(stringId));
            title=mTitle_view.getText().toString();
        }

        Gson mGson=new Gson();
        String json= mGson.toJson(BuriedPoint.buriedPoint(this,title, getClass().getName(),"当前页面Activity"));
        Logger.d(json);
    }

    /**
     * 设置标题文本
     */
    protected void setTitleText(@NonNull String title) {
        mTitle_view = findViewById(R.id.title_view);
        mTitle_view.setText(title);

        insureTopBarVisible();
    }

    /**
     * 显示顶部栏
     */
    private void insureTopBarVisible() {
        if (mTopBarContainer != null && !mTopBarContainer.isShown()) {
            mTopBarContainer.setVisibility(View.VISIBLE);
        }
    }

    /**
     * 隐藏ActionBar
     */
    protected void hideActionBar() {
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null)
            actionBar.hide();
    }

    protected boolean useTransitionAnim() {
        return true;
    }

    @AnimRes
    protected int getEnterAnim() {
        return R.anim.slide_in_from_right;
    }

    @AnimRes
    protected int getExitAnim() {
        return R.anim.fade_out;
    }

    @Override
    public void finish() {
        super.finish();
        if (useTransitionAnim())
            overridePendingTransition(0, getExitAnim());
    }

    @Override
    public void startActivity(Intent intent) {
        super.startActivity(intent);
        if (useTransitionAnim())
            overridePendingTransition(getEnterAnim(), getExitAnim());
    }

    @Override
    public void startActivityForResult(Intent intent, int requestCode) {
        super.startActivityForResult(intent, requestCode);
        if (useTransitionAnim())
            overridePendingTransition(getEnterAnim(), getExitAnim());
    }

    @Override
    public Resources getResources() {
        Resources resources = super.getResources();
        Configuration configuration = new Configuration();
        configuration.setToDefaults();
        resources.updateConfiguration(configuration, resources.getDisplayMetrics());
        return resources;
    }

    protected Context getContext() {
        return this;
    }

    protected BaseActivity getActivity() {
        return this;
    }

    /**
     * 添加订阅
     */
    public void addDisposable(Disposable disposable) {
        if (mCompositeDisposable == null) {
            mCompositeDisposable = new CompositeDisposable();
        }
        mCompositeDisposable.add(disposable);
    }

    /**
     * 取消所有订阅
     */
    protected void clearDisposable() {
        if (mCompositeDisposable != null) {
            mCompositeDisposable.clear();
        }
    }

    public void showProgressDialog(@Nullable String text) {
        runOnUiThread(() -> {
            mProgressContainer.setVisibility(View.VISIBLE);
            mProgressBar.setVisibility(View.VISIBLE);
            mProgressText.setVisibility(TextUtils.isEmpty(text) ? View.GONE : View.VISIBLE);
            mProgressText.setText(text);
            getWindow().setFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE,
                    WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
        });
    }

    public void hideProgressDialog() {
        runOnUiThread(() -> {
            mProgressContainer.setVisibility(View.GONE);
            mProgressBar.setVisibility(View.GONE);
            mProgressText.setVisibility(View.GONE);
            getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
        });
    }

    public void showToast(@StringRes int stringId) {
        showToast(getString(stringId));
    }

    public void showToast(@Nullable CharSequence text) {
        runOnUiThread(() -> {
            hideToast();
            if (mToastView == null) {
                mToastView = View.inflate(BaseApplication.getContext(), R.layout.toast_layout, null);
            }
            ((TextView) mToastView.findViewById(R.id.toast_text)).setText(text);
            mToast = new Toast(BaseApplication.getContext());
            mToast.setView(mToastView);
            mToast.setDuration(Toast.LENGTH_SHORT);
            mToast.setGravity(Gravity.CENTER, 0, DisplayUtil.dip2px2(100f));
            mToast.show();
        });
    }

    public void hideToast() {
        runOnUiThread(() -> {
            if (mToast != null)
                mToast.cancel();
        });
    }

    public void showBindToast(@StringRes int stringId) {
        showBindToast(getString(stringId));
    }

    public void showBindToast(@Nullable String text) {
        runOnUiThread(() -> {
            hideBindToast();
            if (mToastView == null) {
                mToastView = View.inflate(BaseApplication.getContext(), R.layout.toast_layout, null);
            }
            ((TextView) mToastView.findViewById(R.id.toast_text)).setText(text);
            mBindToast = new Toast(BaseApplication.getContext());
            mBindToast.setView(mToastView);
            mBindToast.setDuration(Toast.LENGTH_SHORT);
            mBindToast.setGravity(Gravity.CENTER, 0, DisplayUtil.dip2px2(100f));
            mBindToast.show();
        });
    }

    public void hideBindToast() {
        runOnUiThread(() -> {
            if (mBindToast != null)
                mBindToast.cancel();
        });
    }
}
